<?php
/**
 * 后台用户管理
 * @author Administrator
 *
 */
class userManage extends CControllerManageBase{
	public function show()
	{
		$model = new baseUserModel();
		$pageIndex = $this->getRequestData("page","GET",1);
		$pageSize = 10;
		$c = 0;
		$list = $model->selectPage($pageIndex,$pageSize,"user_id,username,realname,login_count,last_login_time,create_time","del_flag=0","user_id","",$c);
		$pageStr = CPage::showPage($pageIndex,$pageSize,$c);
		$this->setMenu("用户列表");
		$this->render("user/list",array("list"=>$list,"pageStr"=>$pageStr));
	}
	
	public function add(){
		$errorStr="";
		$rule=array(
			"txt_username"=>array(
				"formValidator"=>array("tipid"=>"txt_username_tip","empty"=>"false","onshow"=>"请输入用户名","onfocus"=>"请输入用户名","oncorrect"=>"输入正确"),
				"inputValidator"=>array("min"=>"1","onerror"=>"用户名不能为空"),
				"ajaxValidator"=>array("url"=>$this->_manageDomain."userManage/checkUserName/?isAjax=1","success"=>"function(data){if(data==-1000){alert('没有权限');return false;}else if(data==1){return true;}return false;}","onwait"=>"正在检查用户名...","onerror"=>"用户名已经存在","serverValidateClass"=>"CCustomFormValidator","serverValidateFun"=>"checkUserName")
			),
			"txt_password"=>array(
				"formValidator"=>array("tipid"=>"txt_password_tip","empty"=>"false","onshow"=>"请输入密码","onfocus"=>"请输入密码","oncorrect"=>"输入正确"),
				"inputValidator"=>array("min"=>"1","onerror"=>"密码不能为空")
			),
			"txt_password_re"=>array(
				"formValidator"=>array("tipid"=>"txt_password_re_tip","empty"=>"false","onshow"=>"请输入确认密码","onfocus"=>"请输入确认密码","oncorrect"=>"输入正确"),
				"inputValidator"=>array("min"=>"1","onerror"=>"确认密码不能为空"),
				"compareValidator"=>array("desid"=>"txt_password","operateor"=>"=","onerror"=>"2次密码不一致")
			),
		);
		$this->formValidator->init(array("formID"=>"tbl_base_userForm"));
		$this->formValidator->setRules($rule);
		if($_POST){
			$modelInfo = array();
			$modelInfo["username"] = $this->getRequestData("txt_username");//管理员用户名
			$modelInfo["password"] = CCommon::pwdMd5($this->getRequestData("txt_password"));//管理员密码
			$modelInfo["realname"] = $this->getRequestData("txt_realname");//真名
			if(!$modelInfo["realname"])
			{
				$modelInfo["realname"] = $modelInfo["username"];
			}
			$modelInfo["login_count"] = 0;//登陆次数
			$modelInfo["last_login_time"] = date('Y-m-d H:i:s');//最后一次登录时间
			$modelInfo["create_user"] = "admin";//$this->_userName;//创建人
			$modelInfo["create_time"] = date('Y-m-d H:i:s');//创建时间
			$modelInfo["update_time"] = date('Y-m-d H:i:s');//更新时间
			$modelInfo["del_flag"] = 0;//删除标记，0表示未删除，1表示已删除
			$modelInfo["phone"] = $this->getRequestData("txt_phone");
			$modelInfo["email"] = $this->getRequestData("txt_email");
			$modelInfo["qq"] = $this->getRequestData("txt_qq");
			$modelInfo["remark"] = $this->getRequestData("txt_remark");
			$modelInfo["province"] = $this->getRequestData("sel_province");
			$modelInfo["city"] = $this->getRequestData("sel_city");
			$modelInfo["area"] = $this->getRequestData("sel_area");
			
			$error = $this->formValidator->run();
			if($error){
				$errorStr = "<div><ul>";
				foreach ($error as $item){
					$errorStr .= "<li>".$item."</li>";
				}
				$errorStr .= "</ul></div>";
			}
			else{
				$roleIDList = $this->getRequestData('roleid');
				$roleID = 0;
				if(count($roleIDList))
				{
					$roleID = $roleIDList[0];
				}
				$model=new baseUserModel();
				
				$uid=$model->insert($modelInfo);
				
				$clist = $this->getRequestData("rdCommunity"); //管理的社区
				
				if($uid>0)
				{
					if($roleID)
					{
			       		$roleObj = new userRoleModel();        
			        
						$roleObj->insert(array("user_id"=>$uid,"role_id"=>$roleID));
					}
					
					if($clist)
					{
						foreach($clist as $cid)
						{
							$model->addUserCommunity($uid, $cid);
						}
					}

					$this->sysMsg("新增成功",0,array(array("text"=>"返回用户列表","href"=>$this->_manageDomain."userManage/show/"),array("text"=>"继续新增","href"=>$this->_manageDomain."userManage/add/")));
				}
				else
				{
					$this->sysMsg("新增失败",1);
				}
			}
		}
		
		$roleModel = new roleModel();
		$roleList = $roleModel->selectAll();
		$this->setJsBlock("init('','','',1);_changeSelCallBack=true;_mutiCommunity=true;");
		$this->setStyleFile("/css/validator.css");
		$this->setJsFile(array("/js/formValidator.js","/js/formValidatorRegex.js"));
		$this->setMenu(array(array("text"=>"用户列表","href"=>$this->_manageDomain."userManage/show/"),array("text"=>"用户新增")));
		$this->render("user/add",array("error"=>$errorStr,"roleList"=>$roleList));
	}

	public function edit(){
		$user_id = $this->getRequestData("id","GET");
		$modelInfo = array();
		$errorStr = "";

		$rule=array(
			"txt_password_re"=>array(
				"formValidator"=>array("tipid"=>"txt_password_re_tip","empty"=>"false","onshow"=>"请输入确认密码","onfocus"=>"请输入确认密码","oncorrect"=>"输入正确"),
				"compareValidator"=>array("desid"=>"txt_password","operateor"=>"=","onerror"=>"2次密码不一致")
			),
		);
		$this->formValidator->init(array("formID"=>"tbl_base_userForm"));
		$this->formValidator->setRules($rule);

		$model=new baseUserModel();
		if($_POST){
			$modelInfo["user_id"] = $user_id;
			$modelInfo["password"] = $this->getRequestData("txt_password");//管理员密码
			$modelInfo["realname"] = $this->getRequestData("txt_realname");//真名
			$modelInfo["update_time"] = date('Y-m-d H:i:s');//更新时间
			
			if($modelInfo["password"])
			{
				$modelInfo["password"] = CCommon::pwdMd5($modelInfo["password"]);
			}
			
			$modelInfo["phone"] = $this->getRequestData("txt_phone");
			$modelInfo["email"] = $this->getRequestData("txt_email");
			$modelInfo["qq"] = $this->getRequestData("txt_qq");
			$modelInfo["remark"] = $this->getRequestData("txt_remark");
			$modelInfo["province"] = $this->getRequestData("sel_province");
			$modelInfo["city"] = $this->getRequestData("sel_city");
			$modelInfo["area"] = $this->getRequestData("sel_area");

			$error = $this->formValidator->run();
			if($error){
				$errorStr = "<div><ul>";
				foreach ($error as $item){
					$errorStr .= "<li>".$item."</li>";
				}
				$errorStr .= "</ul></div>";
			}
			else{
				$roleIDList = $this->getRequestData('roleid');
				$roleID = 0;
				if(count($roleIDList))
				{
					$roleID = $roleIDList[0];
				}
				
				$model->update($modelInfo);

		        $roleObj = new userRoleModel();
		        $roleObj->deleteUserRole($user_id);   

		        $clist = $this->getRequestData("rdCommunity"); //管理的社区
		        
		        if($roleID>0)
		        {
					$roleObj->insert(array("user_id"=>$user_id,"role_id"=>$roleID));
		        }

		        $model->delUserCommunity($user_id);
				if($clist)
				{
					foreach($clist as $cid)
					{
						$model->addUserCommunity($user_id, $cid);
					}
				}

		        header("location:".$this->_manageDomain."userManage/show/");
		        exit();
			}
		}

		$modelInfo = $model->selectById($user_id);
		if(!$modelInfo) {
			$this->sysMsg("记录不存在",1);
		}
		$roleObj= new roleModel();
        $roleList=$roleObj->selectAll();
        
        $userRoleObj = new userRoleModel();
        $myRole=$userRoleObj->selectUserRole($user_id); 

        $clist = $model->getUserCommunity($user_id);
        $selID = "";
        foreach ($clist as $item)
		{
			if($selID)
			{
				$selID .= ",";
			}

			$selID .= $item["community_id"];
		}
        
        $this->setViewParam("selID",$selID);
        
        $this->setViewParam("cList",$clist);
        $this->setViewParam("roleList",$roleList);
        $this->setViewParam('myRole', $myRole);

		$this->setViewParam("isAdmin",(Config::get("adminUsername")==$modelInfo["username"]?1:0));
		$this->setJsBlock("init('".$modelInfo["province"]."','".$modelInfo["city"]."','".$modelInfo["area"]."',1);_changeSelCallBack=true;_mutiCommunity=true;getCommunityInfo();");
		$this->setStyleFile("/css/validator.css");
		$this->setJsFile(array("/js/formValidator.js","/js/formValidatorRegex.js"));
		$this->setMenu(array(array("text"=>"用户列表","href"=>$this->_manageDomain."userManage/show/"),array("text"=>"用户修改")));
		$this->render("user/edit",array("error"=>$errorStr,"modelInfo"=>$modelInfo));
	}
	
	public function del()
	{
		$id = $this->getRequestData("id","GET");
		if ($id)
        {
            $buc = new baseUserModel();
            $user = $buc->selectById($id);

            /* admin这个管理员不允许删除 */
            if ($user["username"] == Config::get("adminUsername"))
            {
                $this->sysMsg("不能删除此账号！",1);
            }
            
            elseif ($id == $this->_userID)
            {
                $this->sysMsg("您不能删除自己的账号!",1);
            }
            
			$buc->delete($id);
            $this->show();
        }
	}
	
	public function batchDel()
	{
		$ids = $this->getRequestData("ids","GET");
		
		$idsList = explode(",",$ids);
		
		$buc = new baseUserModel();
		foreach($idsList as $id)
		{
			$user = $buc->selectById($id);
			if ($user["username"] == Config::get("adminUsername"))
            {
                continue;
            }
            elseif ($id == $this->_userID)
            {
                continue;
            }
            $buc->delete($id);
		}
		$this->show();
	}
	
	/**
	 * 验证用户名是否存在
	 */
	public function checkUserName()
	{
		$userName = $this->getRequestData("txt_username",'GET');
		$f = new CCustomFormValidator();
		echo $f->checkUserName($userName)?1:0;
	}
}